package com.tianji.tools;

import cn.hutool.json.JSONUtil;
import com.alibaba.nacos.shaded.io.grpc.internal.JsonUtil;
import com.tianji.api.client.trade.TradeClient;
import com.tianji.api.dto.trade.OrderConfirmVO;
import com.tianji.api.dto.trade.PrePlaceOrder;
import com.tianji.common.utils.UserContext;
import org.springframework.ai.chat.model.ToolContext;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class OrderTool {
    @Autowired
    private TradeClient tradeClient;
    @Autowired
    private StringRedisTemplate redisTemplate;
    public static final String TRADE_PRE_KEY = "preTrade:";

    @Tool(description = "用户所问问题中包含购买时 调用此接口并传入用户要购买的课程id")
    public PrePlaceOrder preTrade(ToolContext toolContext, @ToolParam(description = "课程id") Long courseId) {
        Long userId = (Long) toolContext.getContext().get("userId");
        UserContext.setUser(userId);
        OrderConfirmVO orderConfirmVO = tradeClient.prePlaceOrder(List.of(courseId));
        PrePlaceOrder prePlaceOrder = PrePlaceOrder.of(orderConfirmVO);
        redisTemplate.opsForHash().put(TRADE_PRE_KEY, userId.toString(), JSONUtil.toJsonStr(prePlaceOrder));
        UserContext.removeUser();
        return prePlaceOrder;
    }
}
